<?php

namespace App\Http\Controllers\System;

use App\Package\Tree\Tree;
use App\Models\System\Module;
use App\Http\Controllers\Controller;
use App\Repositories\ModuleRepository;
use App\Http\Requests\System\Module\StoreResource;
use App\Http\Requests\System\Module\UpdateResource;
use App\Http\Requests\System\Module\QueryCollection;

/**
 * 模块管理
 *
 * Date: 21/03/2018
 * @author George
 * @package App\Http\Controllers\System
 */
class ModuleController extends Controller
{
	protected $moduleRepository;

	/**
	 * ModuleController constructor.
	 * @param ModuleRepository $moduleRepository
	 */
	public function __construct(ModuleRepository $moduleRepository)
	{
		$this->moduleRepository = $moduleRepository;
	}

	/**
	 * 获取所有系统模块
	 *
	 * Date: 23/03/2018
	 * @author George
	 * @param QueryCollection $request
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \App\Exceptions\GeneralException
	 */
	public function index(QueryCollection $request)
	{
		// 获取查询参数
		$search = $request->get('search');
		$free = $request->get('free', 0);
		$recursion = $request->get('recursion');

		// 根据名称搜索模块
		if ($search) {
			$this->moduleRepository->where('name', 'like', "%$search%");
		}

		// 获取免费的模块信息
		if ($free) {
			$this->moduleRepository->getFreeModules();
		}

		$modules = $this->moduleRepository->get();

		// 生成树形结构
		if ($recursion) {
			$generator = new Tree();
			$modules = $generator->make($modules, 'code', 'parent_code');
		}

		return success($modules);
	}

	/**
	 * 根据主键获取系统模块
	 *
	 * Date: 21/03/2018
	 * @author George
	 * @param Module $module
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function show(Module $module)
	{
		return success($module);
	}

	/**
	 * 创建系统模块
	 *
	 * Date: 22/03/2018
	 * @author George
	 * @param StoreResource $request
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \App\Exceptions\GeneralException
	 */
	public function store(StoreResource $request)
	{
		$attributes = $request->all();
		$module = $this->moduleRepository->create($attributes);
		return stored($module);
	}

	/**
	 * 更新系统模块属性
	 *
	 * Date: 22/03/2018
	 * @author George
	 * @param $module
	 * @param UpdateResource $request
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \App\Exceptions\GeneralException
	 */
	public function update($module, UpdateResource $request)
	{
		$attributes = $request->all();
		$result = $this->moduleRepository->updateByPrimary($module, $attributes);
		return updated($result);
	}

	/**
	 * 删除资源
	 *
	 * Date: 22/03/2018
	 * @author George
	 * @param $module
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \App\Exceptions\GeneralException
	 */
	public function destroy($module)
	{
		$this->moduleRepository->deleteByPrimary($module);
		return deleted();
	}
}
